package com.iuchannel.android.provider.youtube;

import org.json.JSONArray;
import org.json.JSONObject;

import com.iuchannel.android.provider.Const.YT;
import com.iuchannel.android.provider.util.GetHttp;

import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.MatrixCursor.RowBuilder;


public class User{
	
	public static Cursor getUserPlaylist(String channelId){
		return getUserPlaylist(channelId, YT.DEFAULT_MAX_RESULT);
	}
	
	public static Cursor getUserPlaylist(String channelId, Integer maxResult){
		String url="https://gdata.youtube.com/feeds/api/users/"+channelId+"/playlists?v=2&alt=jsonc&max-results="+maxResult;
		String result=GetHttp.getUrl(url);

		if(result==null || result.length()==0){
			return null;
		}
		
		MatrixCursor m=new MatrixCursor(YT.USER_PLAYLIST);
		try{
		      JSONObject object=new JSONObject(result);
		      JSONObject j=object.getJSONObject("data");
		      
		      //String[] input=new String[YT.USER_PLAYLIST.length];
    		  JSONArray ja=j.getJSONArray("items");
    		  int rowId=0;
    		  for(int n=0;n<ja.length();n++){
    			  RowBuilder r=m.newRow();
    			  JSONObject nthObj=ja.getJSONObject(n);
    			  
    			  try{
    				  for(String s: YT.USER_PLAYLIST){
        		    	  if(s.equals(YT.PRJ_ID)){
        		    		  r.add(rowId++);
        		    	  }else if(s.equals(YT.PRJ_HQDEFAULT)|| s.equals(YT.PRJ_SQDEFAULT)){
        		    		  JSONObject thumbObj=nthObj.getJSONObject(YT.PRJ_THUMNAIL);
        		    		  r.add(thumbObj.getString(s));
        		    	  }else{
        		    		  r.add(nthObj.get(s));
        		    	  }
        		      }    				  
    			  }catch(Exception e){
    				 e.printStackTrace(); 
    			  }
    		  }
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return m;		
	}
	
	
}